import time

import requests
from selenium import webdriver
from selenium.webdriver import ActionChains

from .verifyImg import base64_api


def AutoGetCookie(username, passwd):
    wd = webdriver.Chrome('../浏览器驱动/chromedriver.exe')
    # 打开登录页面
    wd.get('https://passport.bilibili.com/login')

    # 输入账号
    login_username = wd.find_element_by_id('login-username')
    login_username.send_keys(username)

    # 输入密码
    login_passwd = wd.find_element_by_id('login-passwd')
    login_passwd.send_keys(passwd)

    # 点击登录按钮
    login = wd.find_element_by_class_name('btn.btn-login')
    login.click()

    # 休眠5秒
    time.sleep(5)

    # 获取验证图片
    geetest_item_wrap = wd.find_element_by_class_name('geetest_item_wrap')
    img = geetest_item_wrap.find_elements_by_tag_name('img')
    imgurl = img[0].get_attribute('src')

    # 下载验证图片
    Img = requests.get(imgurl)
    with open('../验证码图片/img.jpg', 'wb') as f:
        f.write(Img.content)

    # 调用快识别平台识别验证
    result = base64_api(uname='快识别账号', pwd='快识别密码.', img='../验证码图片/img.jpg')
    print(result)
    print(type(result))

    # 网页图片大小 258.65 289.69
    # 原图大小 344 384
    # 坐标格式：205,209|186,299|300,184|42,215

    # 依次点击汉字验证
    print(img[0].location)
    topX = img[0].location['x']
    topY = img[0].location['y']
    dots = result.split('|')
    for dot in dots:
        print(dot)
        x = topX + int(dot.split(',')[0]) * (258.65 / 344)
        print(x)
        y = topY + int(dot.split(',')[1]) * (289.69 / 384)
        print(y)
        ActionChains(wd).move_by_offset(x, y).click().perform()
        time.sleep(1)
        ActionChains(wd).move_by_offset(-x, -y).perform()  # 将鼠标位置恢复到移动前

    # 提交登录
    geetest_commit_tip = wd.find_element_by_class_name('geetest_commit_tip')
    geetest_commit_tip.click()
    time.sleep(10)

    wd.get('https://bilibili.com/')
    cookies = wd.get_cookies()
    print(cookies)
    path = '../cookie/{}.txt'.format(username)
    with open(path, 'w') as f:
        f.write(str(cookies))

    wd.close()
